//
//  VIPCategoryViewController.swift
//  GhostWorld
//
//  Created by Kam on 2018/5/17.
//  Copyright © 2018 LKGood. All rights reserved.
//

import UIKit

private let categoryCellIdentifier = "VIPCategoryCell"

struct VIPCategoryItem {
  enum ItemType: String {
    case album = "album"
    case group = "group"
  }
  
  var name: String
  var type: ItemType
  var id: Int
  var cover: String
}

class VIPCategoryViewController: VIPChildViewController {

  // MARK: - IBOutlets
  
  @IBOutlet private weak var tableView: UITableView!
  
  // MARK: - Private vars
  
  private var isFirstLoaded = true
  private var categoryItems = [VIPCategoryItem]()
  private var selectedSimpleGroup: SimpleGroup?
  private var selectedAlumbIdentifier: Int = -1
  
  // MARK: - Private methods
  
  private func loadData() {
    API.shared.requestAPI (
      APIURLStrings.vipCategory,
      method: .get,
      header: API.shared.memeberHeader,
      successCallback: { json in
        self.categoryItems = [VIPCategoryItem]()
        if let categories = json["categories"].array {
          categories.forEach {
            let item = VIPCategoryItem (
              name: $0["name"].stringValue,
              type: VIPCategoryItem.ItemType(rawValue: $0["type"].stringValue)!,
              id: $0["id"].intValue,
              cover: $0["cover"].stringValue)
            self.categoryItems.append(item)
          }
        }
        self.tableView.reloadData()
//        UIView.animate(withDuration: 0.3, animations: {
//          self.tableView.alpha = 1
//        })
    }) { message, code in
      loggingPrint("Loading VIP category data failed! \(message)")
    }
  }
  
  // MARK: - Public vars
  
  
  
  // MARK: - Lifecycle
  
  override func viewDidLoad() {
    super.viewDidLoad()
    
    loadData()
  }
  
  override func viewDidAppear(_ animated: Bool) {
    if isFirstLoaded {
      isFirstLoaded = false
    }
  }
  
  override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "ShowVIPCategoryGroupAlbumsSegue" {
      let albumsViewController = segue.destination as! AlbumsViewController
      albumsViewController.simpleGroup = selectedSimpleGroup!
    } else if segue.identifier == "ShowVIPCategoryAlbumDetailSegue" {
      let albumDetailViewController = segue.destination as! AlbumDetailViewController
      albumDetailViewController.albumIdentifier = selectedAlumbIdentifier
      albumDetailViewController.canDisplayBasicInfo = true
    }
  }
  
  override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
  }
  
  // MARK: - IBActions
  
  
  
  // MARK: - Public methods
  
  override func prepareUI() {
    tableView.backgroundColor = .clear
    tableView.tableFooterView = UIView()
//    tableView.alpha = 0
  }
  
  override func getScrollView() -> UIScrollView {
    return tableView
  }
}

// MARK: - UITableViewDataSource

extension VIPCategoryViewController: UITableViewDataSource {
  func numberOfSections(in tableView: UITableView) -> Int {
    return 1
  }
  
  func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return categoryItems.count
  }
  
  func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: categoryCellIdentifier, for: indexPath) as! VIPCategoryCell
    let item = categoryItems[indexPath.row]
    cell.prepare(item: item)
    return cell
  }
}

extension VIPCategoryViewController: UITableViewDelegate {
  
  func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let categoryItem = categoryItems[indexPath.row]
    if categoryItem.type == .group {
      selectedSimpleGroup = SimpleGroup (
        identifier: categoryItem.id,
        name: categoryItem.name
      )
      performSegue(withIdentifier: "ShowVIPCategoryGroupAlbumsSegue", sender: nil)
    } else if categoryItem.type == .album {
      selectedAlumbIdentifier = categoryItem.id
      performSegue(withIdentifier: "ShowVIPCategoryAlbumDetailSegue", sender: nil)
    }
    
    tableView.deselectRow(at: indexPath, animated: true)
  }
  func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return UIScreen.main.bounds.size.width  * 167 / 335
  }
}

// MARK: - UIScrollViewDelegate

extension VIPCategoryViewController: UIScrollViewDelegate {
  func scrollViewDidScroll(_ scrollView: UIScrollView) {
    scrollViewDelegate?.vipChildViewController(self, didScroll: scrollView.contentOffset.y)
  }
}
